const nav = [
  {
    id: 1,
    subitems: [
      {
        id: 2,
        subitems: [
          {
            id: 3,
            subitems: [
              {
                id: 31,
                subitems: []
              }
            ]
          },
          {
            id: 4,
            subitems: []
          }
        ]
      },
      {
        id: 5,
        subitems: []
      }
    ]
  },
  {
    id: 6,
    subitems: []
  }
]

// function flatten(array) {
//   return array.map(item => [].concat(item, ...flatten(item.subitems)))
// }
// console.log(nav);
// console.log(flatten(nav));
// console.log([].concat(...flatten(nav)));

// 用到map
function flatten(array) {
  return [].concat(...array.map(item => [].concat(item, ...flatten(item.subitems))))
}
// 用到for
function flatten(array) {
  let res = [];
  for (const item of array) {
    if (item.subitems.length) {
      // res = res.concat(item, ...flatten(item.subitems));
      // ... 是为了将[]去掉，然后与上层的item一起推入res数组。
      res.push(item, ...flatten(item.subitems));
    } else {
      res.push(item);
    }
  }
  return res;
}

// console.log(nav);
console.log(flatten(nav));

